﻿Imports NVelocity
Imports NVelocity.App
Imports NVelocity.Context

Imports System.Collections.Generic
Imports System.IO

Imports System.Data
Imports System.Data.SqlClient

Partial Class WebForm_ManageEnlistment_EnlistmentPersonCheck
    Inherits System.Web.UI.UserControl

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScriptManager.GetCurrent(Me.Page).RegisterPostBackControl(btnExport)

        'If Not IsPostBack Then
        '    RaiseEvent Loaded(Me, New EventArgs)
        'End If
    End Sub

#Region "DataBinding-將值分散"
    Protected Sub cblStatus_DataBinding(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim cblStatus As CheckBoxList = sender
        Dim gvr As GridViewRow = cblStatus.NamingContainer

        Dim Status As Integer = DataBinder.Eval(gvr.DataItem, "Status").ToString()

        If Status = 1 Then
            cblStatus.Items(0).Selected = True
            cblStatus.Items(1).Selected = False
        ElseIf Status = 2 Then
            cblStatus.Items(0).Selected = False
            cblStatus.Items(1).Selected = True
        ElseIf Status = 3 Then
            cblStatus.Items(0).Selected = True
            cblStatus.Items(1).Selected = True
        Else
            cblStatus.Items(0).Selected = False
            cblStatus.Items(1).Selected = False
        End If

    End Sub

#End Region
    '簽到
    Protected Sub chkAllSignIn_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GV.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignIn"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
    '簽退
    Protected Sub chkAllSignOut_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs)

        Dim chkAll As CheckBox = TryCast(sender, CheckBox)

        For Each row As GridViewRow In Me.GV.Rows
            Dim chk As CheckBox = TryCast(row.FindControl("chkSignOut"), CheckBox)

            chk.Checked = chkAll.Checked
        Next

    End Sub
    Protected Sub GV_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GV.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            Dim chkSignIn As CheckBox = TryCast(e.Row.FindControl("chkSignIn"), CheckBox)
            Dim chkSignOut As CheckBox = TryCast(e.Row.FindControl("chkSignOut"), CheckBox)

       

            Dim chkAllSignIn As CheckBox = TryCast(Me.GV.HeaderRow.FindControl("chkAllSignIn"), CheckBox)
            Dim chkAllSignOut As CheckBox = TryCast(Me.GV.HeaderRow.FindControl("chkAllSignOut"), CheckBox)

            chkAllSignIn.Checked = chkAllSignIn.Checked And chkSignIn.Checked
            chkAllSignOut.Checked = chkAllSignOut.Checked And chkSignOut.Checked
        End If
    End Sub
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Dim i As Integer

        Using scope As New Transactions.TransactionScope

            For Each gvr As GridViewRow In GV.Rows

                'Dim cblStatus As CheckBoxList = gvr.FindControl("cblStatus")

                'i = 0

                'If cblStatus.Items(0).Selected = True Then
                '    i += 1
                'End If

                'If cblStatus.Items(1).Selected = True Then
                '    i += 2
                'End If
                Dim chkSignIn As CheckBox = TryCast(gvr.FindControl("chkSignIn"), CheckBox)
                Dim chkSignOut As CheckBox = TryCast(gvr.FindControl("chkSignOut"), CheckBox)
                i = 0

                If chkSignIn.Checked = True Then
                    i += 1
                End If

                If chkSignOut.Checked = True Then
                    i += 2
                End If

                sql.AppendFormat("UPDATE EnlistTrainingRecord SET Status={0} WHERE CourseID='{1}' and VolunteerID='{2}'", i, GV.DataKeys(gvr.RowIndex).Values.Item(0), GV.DataKeys(gvr.RowIndex).Values.Item(1))

            Next

            If sql.Length <> 0 Then
                dat.AccData(sql.ToString(), Nothing, Data.CommandType.Text)
            End If

            scope.Complete()

            'MyObj.ShowMessage("888")

        End Using

        MyObj.ShowMessage("儲存成功")

    End Sub

    Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click

        Dim dat As New clsData
        Dim ResultDataTable As Data.DataView = Me.SqlDataSource1.Select(New DataSourceSelectArguments())

        If ResultDataTable IsNot Nothing AndAlso ResultDataTable.Count > 0 Then
            'Prepare Data

            Dim base As Integer = 16

            Dim vList As New List(Of TrainingRegister)
            Dim v As TrainingRegister


            'For i As Integer = 1 To base

            Dim i As Integer = 1
            Dim prevRegionID As String

            For Each dr As DataRowView In ResultDataTable
                If prevRegionID <> "" AndAlso prevRegionID <> dr("RegionID") Then

                    For j As Integer = (i Mod base) To base
                        v = New TrainingRegister
                        v.Name = ""
                        v.VillageName = ""
                        v.Index = i
                        v.RegStatus = ""
                        vList.Add(v)

                        i = i + 1
                    Next

                    i = 1
                End If

                v = New TrainingRegister
                v.Name = dr("VolunteerName").ToString()
                v.VillageName = dr("RegionName").ToString()
                'v.RegStatus = dr("RegStatusText").ToString()
                v.RegStatus = ""
                v.Index = i
                vList.Add(v)

                If i Mod base = 1 Then
                    v.IsHeader = True
                Else
                    v.IsHeader = False
                End If

                i += 1
                prevRegionID = dr("RegionID")

            Next

            For j As Integer = (i Mod base) To base
                v = New TrainingRegister
                v.Name = ""
                v.VillageName = ""
                v.Index = i
                v.RegStatus = ""
                vList.Add(v)

                i = i + 1
            Next

            'header data
            Dim sql As New MyStringBuilder

            sql.AppendFormat("select eh.* ")
            sql.AppendFormat(", o.OrganizationName ")
            sql.AppendFormat("from EnlistTrainingCourse ec ")
            sql.AppendFormat("inner join EnlistHeader eh on ec.EnlistID = eh.EnlistID ")
            sql.AppendFormat("inner join OrganizationView o on eh.UOrganizationID = o.UOrganizationID ")
            sql.AppendFormat("where ec.CourseID = {0} ", Me.CourseID)

            Dim trainingGroupInfo As Data.DataTable = dat.GetData(sql)

            'Print

            Dim fileName As String = "TrainingRegister.xls"
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName)
            Response.ContentType = "application/vnd.ms-excel"

            Dim velocity As New VelocityEngine
            Dim props As New Commons.Collections.ExtendedProperties

            'fix bug
            props.AddProperty("file.resource.loader.path", Server.MapPath("~\App_Data"))
            props.AddProperty("input.encoding", "utf-8")
            props.AddProperty("output.encoding", "utf-8")
            velocity.Init(props)

            Dim template As Template

            Dim context As New VelocityContext

            template = velocity.GetTemplate("在職訓練簽到表範例.xml")

            context.Put("StartYear", DateTime.Parse(trainingGroupInfo.Rows(0)("StartDate")).Year - 1911)
            context.Put("StartDate", DateTime.Parse(trainingGroupInfo.Rows(0)("StartDate")).ToString("MM/dd"))
            context.Put("OrganizationName", trainingGroupInfo.Rows(0)("OrganizationName").ToString())
            context.Put("PrintRowCount", vList.Count + 2)
            context.Put("VolunteerList", vList)
            context.Put("User", clsAuth.GetUserID())
            context.Put("DownloadDate", Today.Year.ToString() & "-" & Today.Month.ToString() & "-" & Today.Day.ToString() & "T" & Now.Hour.ToString() & ":" & Now.Minute.ToString() & ":" & Now.Second.ToString() & "Z")
            context.Put("IP", MyObj.getIP())
            Dim writer As New IO.StringWriter
            template.Merge(context, writer)

            Response.Write(writer.GetStringBuilder().ToString())

            Response.End()

        Else

            MyObj.ShowMessage(Me.GetLocalResourceObject("NoData"))

        End If

    End Sub

    Public Class TrainingRegister
        Private NameField As String
        Private VillageNameField As String
        Private TownNameField As String
        Private IndexField As Integer
        Private IsHeaderField As Boolean

        Public Property Name() As String
            Get
                Return Me.NameField
            End Get
            Set(ByVal value As String)
                Me.NameField = value
            End Set
        End Property

        Public Property VillageName() As String
            Get
                Return Me.VillageNameField
            End Get
            Set(ByVal value As String)
                Me.VillageNameField = value
            End Set
        End Property

        Public Property TownName() As String
            Get
                Return Me.TownNameField
            End Get
            Set(ByVal value As String)
                Me.TownNameField = value
            End Set
        End Property

        Public WriteOnly Property IsHeader() As Boolean
            Set(ByVal value As Boolean)
                Me.IsHeaderField = value
            End Set
        End Property

        Public ReadOnly Property CellText() As String
            Get
                If Me.IsHeaderField = True Then
                    Return "<Cell ss:MergeDown=""15"" ss:StyleID=""s52""><Data ss:Type=""String""></Data><NamedCell ss:Name=""Print_Area""/></Cell>"
                Else
                    Return ""
                End If
            End Get
        End Property

        Public ReadOnly Property CellText2() As String
            Get
                If Me.IsHeaderField = True Then
                    Return ""
                Else
                    Return "ss:Index=""2"""
                End If
            End Get
        End Property

        Public Property Index() As Integer
            Get
                Return Me.IndexField
            End Get
            Set(ByVal value As Integer)
                Me.IndexField = value
            End Set
        End Property

        Private RegStatusField As String

        Public Property RegStatus() As String
            Get
                Return Me.RegStatusField
            End Get
            Set(ByVal value As String)
                Me.RegStatusField = value
            End Set
        End Property

    End Class

    Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource1.Selecting

        SqlDataSource1.SelectParameters.Item("CourseID").DefaultValue = Me.CourseID
    End Sub
End Class

Partial Class WebForm_ManageEnlistment_EnlistmentPersonCheck
   
    Public Sub InitData(ByVal intCourseID As Integer)

        Dim dat As New clsData
        Dim sql As New MyStringBuilder

        Using scope As New Transactions.TransactionScope

            '新增-EnlistRecord多於EnlistTrainingCourse的資料
            sql.AppendFormat("INSERT EnlistTrainingRecord(CourseID, VolunteerID,Status, CreateDate, CreateBy) ")
            sql.AppendFormat("SELECT B.CourseID,A.VolunteerID,0,getdate(),'{0}' ", Page.User.Identity.Name)
            sql.AppendFormat("FROM EnlistRecord A ")
            sql.AppendFormat("inner join EnlistTrainingCourse B on A.EnlistID=B.EnlistID and B.CourseID={0} ", intCourseID)
            sql.AppendFormat("left join EnlistTrainingRecord C on B.CourseID=C.CourseID and A.VolunteerID=C.VolunteerID ")
            sql.AppendFormat("WHERE C.VolunteerID Is null; ")

            '刪除-EnlistTrainingCourse多於EnlistRecord的資料
            sql.AppendFormat("DELETE A ")
            sql.AppendFormat("FROM EnlistTrainingRecord A ")
            sql.AppendFormat("inner join EnlistTrainingCourse B on A.CourseID=B.CourseID AND A.CourseID={0} ", intCourseID)
            sql.AppendFormat("left join EnlistRecord C on B.EnlistID=C.EnlistID and A.VolunteerID=C.VolunteerID ")
            sql.AppendFormat("WHERE C.VolunteerID Is null; ")

            dat.AccData(sql)

            scope.Complete()

        End Using

        Me.CourseID = intCourseID
        'MyObj.ShowMessage(Me.CourseID)

        SqlDataSource1.SelectParameters.Item("CourseID").DefaultValue = Me.CourseID
        GV.DataSourceID = SqlDataSource1.ID
        'GV.DataBind()


    End Sub

    Private Property CourseID() As Integer
        Get
            Return ViewState("CourseID")
        End Get
        Set(ByVal value As Integer)
            ViewState("CourseID") = value
        End Set
    End Property
End Class